package com.example.dingding.controller;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiUserGetuserinfoRequest;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.response.OapiUserGetuserinfoResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.example.dingding.config.HttpHelper;
import com.example.dingding.service.LoginService;
import com.example.dingding.util.ResponseResult;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 企业内部应用免登
 *
 * @author openapi@dingtalk
 * 2020-11-3
 */
@RestController
public class LoginController {

    @Autowired
    private HttpHelper httpHelper;


    @Autowired
    private LoginService loginService;

    /**
     * 欢迎页面，通过 /welcome 访问，判断后端服务是否启动
     *
     * @return 字符串 welcome
     */
    @GetMapping("/welcome")
    public String welcome() {
        return "welcome";
    }

    /**
     * @param requestAuthCode
     * @return ServiceResult
     * 2020-11-3
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ResponseResult<Map<String, Object>> login(@RequestParam("code") String requestAuthCode) {
        // 获取access_token，注意正式代码要有异常流处理
        String access_token = httpHelper.getAccess_Token();
        // 获取用户信息
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo");
        OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
        request.setCode(requestAuthCode);
        request.setHttpMethod("GET");
        OapiUserGetuserinfoResponse response;
        try {
            response = client.execute(request, access_token);
        } catch (ApiException e) {
            e.printStackTrace();
            return null;
        }
        // 查询得到当前用户的userId
        // 获得到userId之后应用应该处理应用自身的登录会话管理（session）,避免后续的业务交互（前端到应用服务端）每次都要重新获取用户身份，提升用户体验
        String userId = response.getUserid();

        //免登
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("userId", userId);
        String userInfo = getUserInfo(access_token, userId);
        returnMap.put("userInfo", userInfo);
        returnMap.put("access_token", "access_token");
        System.out.println();
        return ResponseResult.okResult(returnMap);
    }


    /**
     * jsApi鉴权
     * @param type 应用类型
     * @return
     */
    @PostMapping("/auth/{type}")
    public ResponseResult auth(@PathVariable String type) {
        return loginService.auth(type);
    }

    /*
    *查询用户详情
    * */
    @GetMapping("/getUserInfo/{userIds}")
    public ResponseResult getUserInfo(@PathVariable List<String> userIds) {
        return loginService.getUserInfo(userIds);
    }


    private String getUserInfo(String access_token, String userId) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            req.setUserid(userId);
            req.setLanguage("zh_CN");
            OapiV2UserGetResponse rsp = client.execute(req, access_token);
            return rsp.getBody();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }
}
